import MQTT from 'mqtt'

const mqttId = Math.random().toString(36).substr(2);

const topicList = {};
const option = {
  clean: true,
  connectTimeout: 4000,
  clientId: mqttId,
  username: 'name+' + mqttId,
  password: 'pswd+' + mqttId
}

const connectUrl = 'ws://localhost:8083/mqtt';
const emqx = MQTT.connect(connectUrl, option);

emqx.on('connect', () => {
  console.log('mqtt服务器连接成功', connectUrl);
}).on('error', (err) => [
  console.log('MQTT连接失败，出现异常:', err)
]).on('message', (topic, payload) => {
  let msgJson = JSON.parse(payload);
  if(!topicList[topic]) return;
  topicList[topic](msgJson);
})

emqx.subscribeTopic = function(topic, callback) {
  if(typeof(topic) !== 'string' || typeof(callback) !== 'function') {
    console.log('输入的话题或者回调函数格式不正确');
    return;
  }
  emqx.subscribe(topic);
  topicList[topic] = callback;
}

export {
  emqx
}